// 对基本操作进行封装 
var {getUserId_,getAccess_token_,doGET_,getUserInfo_}  = require('./request.js');
var {setValue_,getValue_,exists_} = require('./redis.js');
var {existUser_,addUser_} = require('./mysql.js');


//bhHmxK200i9EOJk975cH_dC0Rtqsvk7c-PptymgJg0o-k4KAyd8kbSpfSisCI_xplAy58YeFCqHdoFwkJ2C-uxBYxeBYMN6JbHWra2hHbiziYIpnCAVnZdd_Yr_kl0wNUflN8tgmchvvUq5TSK7UnPjKjTHIsofKxW1ni32AZfdEt4bTiZRDgyjad54xQJ8Blj6FKrVR8cBbmV4i9NZDCw
// 获取用户id 
var getUserId = (access_token,code)=>{
	return new Promise((resolve,reject)=>{
        getUserId_(access_token,code).then(result=>{
        	// access_token 过期
        	if(result.errcode == '42001'){
        		console.log('过期');
        		getAccess_token_().then(access_token=>{
        			setValue_('access_token',access_token);
        			getUserId_(access_token,code).then(data=>{
        				resolve(data.UserId);
        			})
        		});
        	}else if(result.errcode == '0'){
        		resolve(result.UserId);
        	}
        }) 
    })
}

// 获取access_token
var getAccess_token = ()=>{
	return new Promise((resolve,reject)=>{
        exists_('access_token').then(exist =>{
        	if(exist){
        		// 从redis中获取
        		getValue_('access_token').then(access_token=>{
        			resolve(access_token);
        		});
        	}else{
        		// 重新生成
        		getAccess_token_().then(access_token=>{
        			setValue_('access_token',access_token).then(data=>{
        				resolve(access_token);
        			});
        		});
        	}
        })
    })
}

// 保存用户信息
var saveUser  = (access_token,userid)=>{
	return new Promise((resolve,reject)=>{
    	existUser_(userid).then(exist=>{
    		if(!exist){
    			console.log('用户不存在');
    			getUserInfo_(access_token,userid).then(userInfo=>{
    				var user = {
	                    user_id:userInfo.userid,
	                    user_name:userInfo.name,
	                    user_mobile:userInfo.mobile
	                } 
	                addUser_(user).then(result =>{
	                	resolve(result);
	    			});
    			})
    		}
    		resolve(true); 
    	})
    })
}

// 发送get请求
var doGET = (url)=>{
	return new Promise((resolve,reject)=>{
        doGET_(url).then(data=>{
        	resolve(data);
        });
    })
}


exports.getUserId = getUserId
exports.getAccess_token = getAccess_token
exports.doGET = doGET
exports.saveUser = saveUser